import { useEffect } from "react";
import { Card, Form, Input, Button, message } from "antd";
import { useNavigate, Link, useParams } from "react-router-dom";
import {
  reqAddHospitalSet,
  reqGetHospitalSetById,
  reqUpdateHospitalSet,
} from "@/api/hospital/hospitalSet";
import type { AddHospitalSetParams } from "@/api/hospital/hospitalSet/types";

export default function HospitalSetAdd() {
  const navigate = useNavigate();
  // 表单提交触发的函数（表单校验全部通过才触发，有一个失败就不触发了）
  const onFinish = async (values: AddHospitalSetParams) => {
    if (id) {
      // 修改
      await reqUpdateHospitalSet({
        ...values,
        id: +id,
      });
      message.success("修改医院设置成功");
    } else {
      // 添加
      await reqAddHospitalSet(values);
      message.success("添加医院设置成功");
    }

    navigate(-1);
  };

  const [form] = Form.useForm();
  // 获取params参数
  const params = useParams<{ id: string }>();
  const id = params.id;

  useEffect(() => {
    if (!id) return; // 添加医院不要发送请求
    const getHospitalSetById = async () => {
      const res = await reqGetHospitalSetById(+id);
      // 设置表单项的值
      // https://ant-design.antgroup.com/components/form-cn#forminstance
      form.setFieldsValue(res);
    };
    getHospitalSetById();
  }, [id, form]);

  return (
    <Card>
      {/* 
        栅格系统：一行分为24等份
          labelCol   左侧文本大小
          wrapperCol 右侧表单控件大小
      */}
      <Form
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 8 }}
        onFinish={onFinish}
        form={form}
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[
            { required: true, message: "请输入医院名称" },
            // 规则文档：https://ant-design.antgroup.com/components/form-cn#rule
            // { min: 2, max: 10, message: "xxx" },
          ]}
        >
          <Input placeholder="请输入医院名称" />
        </Form.Item>
        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "请输入医院编号" }]}
        >
          <Input placeholder="请输入医院编号" />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "请输入api基础路径" }]}
        >
          <Input placeholder="请输入api基础路径" />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "请输入联系人姓名" }]}
        >
          <Input placeholder="请输入联系人姓名" />
        </Form.Item>
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[{ required: true, message: "请输入联系人手机" }]}
        >
          <Input placeholder="请输入联系人手机" />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 3 }}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Link to="/syt/hospital/hospitalset">
            <Button>返回</Button>
          </Link>
        </Form.Item>
      </Form>
    </Card>
  );
}
